package cc.ufinity.networkdiagnose.widget;

import java.io.File;
import java.util.Date;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.Camera;
import android.media.ToneGenerator;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.format.DateFormat;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.widget.Button;
import cc.ufinity.networkdiagnose.app.GlobalApp;
import cc.ufinity.networkdiagnose.manager.Account;
import cc.ufinity.networkdiagnose.manager.DBManager;
import cc.ufinity.networkdiagnose.manager.MessageWhat;
import cc.ufinity.networkdiagnose.manager.Task;
import cc.ufinity.networkdiagnose.manager.WebAuthManager;
import cc.ufinity.networkdiagnose.manager.WlanManager;
import cc.ufinity.networkdiagnose.view.R;

public class CameraWidget extends GeneralTestWidget {

	private Activity ctx;

	public final static String PREFS_NAME = "mymobile";
	public final static String PREFS_KEY = "number";
	private final static String TAG = "CameraActivity";
	private final String ACTION_NAME = "camera";
	private final String ACTION_NAME_CANCEL = "cameraCancel";

	// private static final Object TAG_REFER_RESULTWLAN = null;
	private SurfaceView surfaceView;
	private SurfaceHolder surfaceHolder;
	private Camera camera;
	private File picture;
	private Button btnSave;
	private Handler handler;
	private Button backBtn;
	private Task task;
	private ToneGenerator tone;
	private String resultPage = "";

	public CameraWidget(Activity context) {
		super(context);
		this.ctx = context;
		registerBoradcastReceiver();
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		ctx.startActivityForResult(intent, 1);
		task = (Task) ctx.getIntent().getSerializableExtra(TAG_CAMERA_TASK);
		// setupViews();
		handler = new Handler() {
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case MessageWhat.FTP_ACCOUNT_INVALID:
					showMessage(ctx, "无法获取FTP账号，请检查FTP配置.");
					break;
				case MessageWhat.FTP_UPLOAD_TASK_DONE:
					showMessage(ctx, "上传成功.");
					break;
				case MessageWhat.FTP_UPLOAD_FAILED:
					showMessage(ctx, "上传失败，请检查FTP配置是否正确.");
					break;
				case MessageWhat.FTP_LOGIN_FAILED:
					showMessage(ctx, "FTP登录失败，请检查FTP配置是否正确.");
					break;
				}
			}
		};
	}

	private void upload(final String fname) {
		if (task.scanResult != null
				&& task.scanResult.SSID.equals(WlanManager.SSID_CMCC)) {
			WebAuthManager wManager = new WebAuthManager(ctx);
			String defaultUrl = ctx.getResources().getString(
					R.string.default_url);
			DBManager db = new DBManager(ctx);
			Account config = db.getAccount();
			String userName = "", pwd = "";
			if (null != config) {
				userName = config.userName;
				pwd = config.password;
			}
			wManager.auth(defaultUrl, userName, pwd);
			db.release();
		}
		System.err.println("=========================照片名称：" + fname);
		if (null != fname) {
			showMessage(ctx, "正在上传截屏...");
			new Thread() {
				public void run() {
					uploadPic(fname, ctx, handler);
				}
			}.start();
		}
		ctx.getIntent().putExtra(TAG_REFER_TASK, task);
		ctx.getIntent().putExtra(TAG_CAMERA_FLAG, TAG_CAMERA_FLAG_VALUE);
		resultPage = (String) ctx.getIntent().getSerializableExtra(
				TAG_REFER_RESULT_FLAG);
		if (resultPage != null && resultPage.equals(TAG_REFER_RESULTALL))
			ctx.setContentView(new TaskResultAll(ctx));
		else if (resultPage != null && resultPage.equals(TAG_REFER_RESULTTD))
			ctx.setContentView(new TaskResultTD(ctx));
		else if (resultPage != null && resultPage.equals(TAG_REFER_RESULTGSM))
			ctx.setContentView(new TaskResultGSM(ctx));
		else if (resultPage != null && resultPage.equals(TAG_REFER_RESULTWALN))
			ctx.setContentView(new TaskResultWlan(ctx));
		// ================
		else if (resultPage != null && resultPage.equals(TAG_REFER_RESULTALL2))
			ctx.setContentView(new TaskResultAll(ctx));
		else if (resultPage != null && resultPage.equals(TAG_REFER_RESULTTD2))
			ctx.setContentView(new TaskResultTD(ctx));
		else if (resultPage != null && resultPage.equals(TAG_REFER_RESULTGSM2))
			ctx.setContentView(new TaskResultGSM(ctx));
		else if (resultPage != null && resultPage.equals(TAG_REFER_RESULTWALN2))
			ctx.setContentView(new TaskResultWlan(ctx));
	}

	public void registerBoradcastReceiver() {
		IntentFilter myIntentFilter = new IntentFilter();
		myIntentFilter.addAction(ACTION_NAME);
		myIntentFilter.addAction(ACTION_NAME_CANCEL);
		// 注册广播
		ctx.registerReceiver(mBroadcastReceiver, myIntentFilter);
	}

	private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			System.out.println("action:-----------------" + action);
			if (action.equals(ACTION_NAME)) {
				String fileName = intent.getStringExtra("fileName");
				
				String fname = DateFormat.format("yyyyMMddhhmmss", new Date())
						.toString() + ".jpg";
				if (task != null && task.id != null && !task.id.equals(""))
					fname = task.id + "_" + fname;
				else {
					fname = task.testPhone + "_" + fname;
				}
				File fileDir1 = ctx.getFilesDir();
		        String path = fileDir1.getParent()+ File.separator + "wlantest" + File.separator;
				File file = new File(path + fileName);
				file.renameTo(new File(path + fname));
				
				
				
				upload(fname);
				// Toast.makeText(Test.this, "处理action名字相对应的广播", 200);
			} else {
				back();
			}
		}

	};

	private void back() {
		// if (mBroadcastReceiver!=null) {
		// ctx.unregisterReceiver(mBroadcastReceiver);
		// }
		ctx.getIntent().putExtra(TAG_REFER_TASK, task);
		ctx.getIntent().putExtra(TAG_CAMERA_FLAG, TAG_CAMERA_FLAG_VALUE);
		resultPage = (String) ctx.getIntent().getSerializableExtra(
				TAG_REFER_RESULT_FLAG);
		if (resultPage != null && resultPage.equals(TAG_REFER_RESULTALL))
			ctx.setContentView(new TaskResultAll(ctx));
		else if (resultPage != null && resultPage.equals(TAG_REFER_RESULTTD))
			ctx.setContentView(new TaskResultTD(ctx));
		else if (resultPage != null && resultPage.equals(TAG_REFER_RESULTGSM))
			ctx.setContentView(new TaskResultGSM(ctx));
		else if (resultPage != null && resultPage.equals(TAG_REFER_RESULTWALN))
			ctx.setContentView(new TaskResultWlan(ctx));
		// ================
		else if (resultPage != null && resultPage.equals(TAG_REFER_RESULTALL2))
			ctx.setContentView(new TaskResultAll(ctx));
		else if (resultPage != null && resultPage.equals(TAG_REFER_RESULTTD2))
			ctx.setContentView(new TaskResultTD(ctx));
		else if (resultPage != null && resultPage.equals(TAG_REFER_RESULTGSM2))
			ctx.setContentView(new TaskResultGSM(ctx));
		else if (resultPage != null && resultPage.equals(TAG_REFER_RESULTWALN2))
			ctx.setContentView(new TaskResultWlan(ctx));
	}
}
